//
//  ViewController.swift
//  net
//
//  Created by China Dragon on 2023/8/21.
//

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        /*
         swift3.0：NSURLSession的使用
         https://blog.csdn.net/weixin_34152820/article/details/85872930
         */
        
        let str_url:String = "http://t.weather.itboy.net/api/weather/city/101030100"
        let url = URL(string: str_url)
        let urlRequest: URLRequest = URLRequest(url: url!)
//        let dataTask = URLSession.shared.dataTask(with: urlRequest) {  (data:Data?, response:URLResponse?, error:Error?) in
        let dataTask = URLSession.shared.dataTask(with: urlRequest) {  (data:Data?, _, error: Error?) in // 如果不关心的参数可以使用 下划线 _
            
            if(error == nil){
                
                let jsonstr = "[\"hello\",\"world\"]"
                let jsondata = jsonstr.data(using:  String.Encoding.utf8)
                
                if(data == nil){
                    print("响应数据为 nil ")
                    return
                }
                
                do{
                    //反序列化
//                    let dic = try JSONSerialization.jsonObject(with: data!,options: JSONSerialization.ReadingOptions.fragmentsAllowed)
                    let dic = try JSONSerialization.jsonObject(with: jsondata!,options: JSONSerialization.ReadingOptions.fragmentsAllowed)
                    print("dic 反序列化 结果 \(dic)")
                    /*
                     dic 反序列化 结果 (
                         hello,
                         world
                     )

                     */
//                }catch let error{
                }catch {
                    print("反序列化异常：\(error.localizedDescription)")
                    //  使用  let jsonstr = "\"hello\",\"world\"]" ，少了 [
                    //反序列化异常：The data couldn’t be read because it isn’t in the correct format.

                }
                
               
                
                
                
            }else{
                print("网络请求异常：\(error!.localizedDescription)")
            }
            
        }as URLSessionDataTask
        
        dataTask.resume()
        
    }


}

